﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using MH.Lib.Data;

namespace MH.Lib.Serialization
{
    public class TxtSerializer
        : ISerializer
    {
        #region ISerializer

        /// <summary>
        /// Attempts to serialize data to given filename
        /// </summary>
        /// <param name="data"> Source data </param>
        /// <param name="filename"> Target filename </param>
        /// <returns> True if successful, false otherwise </returns>
        public bool Serialize(IPersonContainer data, string filename)
        {
            try
            {
                // Create stream writer
                var encoding = new UTF8Encoding();
                using (StreamWriter writer = new StreamWriter(new FileStream(filename, FileMode.Create), encoding))
                {
                    // Serialize each person in container
                    foreach (var person in data)
                        writer.WriteLine(person);
                }

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// Attempts to deserialize data from given filename
        /// </summary>
        /// <param name="filename"> Source filename </param>
        /// <param name="data"> Target data </param>
        /// <returns> True if successful, false otherwise </returns>
        public bool Deserialize(string filename, out IPersonContainer data)
        {
            data = new PersonContainer();

            try
            {
                using (StreamReader reader = File.OpenText(filename))
                {
                    String line;
                    string[] separators = { "\t" };
                    while ((line = reader.ReadLine()) != null)
                    {
                        // Split current line according to separators
                        string[] temp = line.Split(separators, StringSplitOptions.None);
                        if (temp == null || temp.Length != 3)
                            continue;

                        // Create new person
                        var person = new Person(temp[0], temp[1], temp[2]);

                        // Insert to container
                        data.Insert(person);
                    }
                }

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        #endregion // ISerializer
    }
}
